package cn.ug.msg.web.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.List;

public class HttpClientUtil {
    protected static Log log = LogFactory.getLog(HttpClientUtil.class);


    public static String invokeHttp(String url, List<NameValuePair> nvps) {
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        try {
            if(nvps != null && nvps.size() > 0) {
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            }
            CloseableHttpResponse httpResponse = closeableHttpClient.execute(httpPost);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if(statusCode == 200) {
                return EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
            }
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            httpPost.releaseConnection();
        }

        return null;
    }
}
